package com.kx.kxblog.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.MapSession;
import org.springframework.session.MapSessionRepository;
import org.springframework.session.SessionRepository;
import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Configuration
@EnableSpringHttpSession
public class MyWebConfig implements WebMvcConfigurer {

    @Autowired
    private KxBlogProperties kxBlogProperties;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        Map<List<String>, List<String>> resourceMap = new LinkedHashMap<>();
        resourceMap.put(Collections.singletonList("/**"), Arrays.asList("classpath:/web/", "file:" + kxBlogProperties.getWebLocation()));
        for(Map.Entry<List<String>, List<String>> entry : resourceMap.entrySet()){
            List<String> pattern = entry.getKey();
            List<String> locations = entry.getValue();
            registry.addResourceHandler(pattern.toArray(new String[0])).addResourceLocations(locations.toArray(new String[0]));
            log.info("已配置静态资源路径：{}->{}", pattern, locations);
        }
    }

    @Bean
    public HeaderHttpSessionIdResolver headerHttpSessionIdResolver() {
        return new HeaderHttpSessionIdResolver(kxBlogProperties.getTokenName());
    }
    @Bean
    public SessionRepository<MapSession> sessionRepository() {
        return new MapSessionRepository(new ConcurrentHashMap<>());
    }
}
